package com.zidian.study.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.bean.EvaluateCustomBean;
import com.zidian.study.globa.Constant;
import com.zidian.study.utils.GetUserInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * Created by GongCheng on 2016/11/30.
 */

public class EvaHotAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_ITEM = 1;
    private static final int TYPE_FOOTER = 2;
    private static boolean hasMore = true;

    private Context context;
    private List<EvaluateCustomBean.DataBean.ListBean> datas;

    public EvaHotAdapter(Context context, List<EvaluateCustomBean.DataBean.ListBean> datas) {
        this.context = context;
        this.datas = datas;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == TYPE_ITEM) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_evaluate_custom_req, parent, false);
            return new ItemViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_interaction_ask_foot, parent, false);
            return new FooterViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder,  int position) {
        if (holder instanceof ItemViewHolder) {
            ((ItemViewHolder) holder).evaluateCustomContent.setText(datas.get(position).getEvaluationcontent());
            ((ItemViewHolder) holder).evaluateCustomName.setText(datas.get(position).getMynickname());
            ((ItemViewHolder) holder).evaluateCustomTime.setText(datas.get(position).getEvaluationtime());
            Glide.with(context)
                    .load(datas.get(position).getAppraiserurl())
                    .placeholder(R.drawable.student)
                    .into(((ItemViewHolder) holder).evaluateCustomImage);
            //设置点赞状态

            ((ItemViewHolder) holder).evaSupportCountTv.setText(datas.get(position).getLikenum() + "");
            if (datas.get(position).getLikenumtype() == 1) {
                ((ItemViewHolder) holder).evaSupportIv.setImageResource(R.drawable.ic_supported);
            } else {
                ((ItemViewHolder) holder).evaSupportIv.setImageResource(R.drawable.ic_support);
            }

            ((ItemViewHolder) holder).evaSupportIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getLayoutPosition();
                    if (datas.get(position).getLikenumtype() == 1) {//取消点赞
                        ((ItemViewHolder) holder).evaSupportIv.setImageResource(R.drawable.ic_support);
                        ((ItemViewHolder) holder).evaSupportCountTv.setText(datas.get(position).getLikenum() - 1 + "");
                        unSupportEva(datas.get(position ).getCustomevaluationid() + "");
                        //更新数据源，防止item复用之后无法保存状态
                        datas.get(position).setLikenumtype(0);
                        datas.get(position).setLikenum(datas.get(position).getLikenum() - 1);
                    } else {
                        ((ItemViewHolder) holder).evaSupportIv.setImageResource(R.drawable.ic_supported);
                        ((ItemViewHolder) holder).evaSupportCountTv.setText(datas.get(position).getLikenum() + 1  + "");
                        supportEva(datas.get(position).getByevaluatepersonid(), datas.get(position).getCustomevaluationid() + "");
                        //更新数据源，防止item复用之后无法保存状态
                        datas.get(position).setLikenumtype(1);
                        datas.get(position).setLikenum(datas.get(position).getLikenum() + 1);
                    }
                }
            });
            //设置删除评论
            ((ItemViewHolder) holder).evaDeleteIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getLayoutPosition();
                    if (datas.get(position).getDeltype() == 1) {
                        deleteEva(datas.get(position).getCustomevaluationid() + "");
                        datas.remove(position);
                        if (datas.size() == 0) {
                            notifyDataSetChanged();
                        } else {
                            notifyItemRemoved(position);
                        }
                    } else {
                        return;
                    }
                }
            });

            //设置能否删除评论
            if (datas.get(position).getDeltype() == 1) {
                ((ItemViewHolder) holder).evaDeleteIv.setVisibility(View.VISIBLE);
            } else {
                ((ItemViewHolder) holder).evaDeleteIv.setVisibility(View.GONE);
            }

        } else if (holder instanceof FooterViewHolder) {
            if (!hasMore) {
                ((FooterViewHolder) holder).loadText.setText("全部数据加载完成!");
                ((FooterViewHolder) holder).progressBar.setVisibility(View.GONE);
            } else {
                ((FooterViewHolder) holder).loadText.setText("正在加载...");
                ((FooterViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
            }

        }
    }

    @Override
    public int getItemCount() {
        return datas.size() == 0 ? 0 : datas.size() + 1;
    }

    @Override
    public int getItemViewType(int position) {

        if (position +1 == getItemCount()) {
            return TYPE_FOOTER;
        } else {
            return TYPE_ITEM;
        }

    }

    public void addDatas(List<EvaluateCustomBean.DataBean.ListBean> datas) {
        this.datas.addAll(datas);
        notifyDataSetChanged();
    }


    public void clearDatas(){
        datas.clear();
        notifyDataSetChanged();
    }

    public void setHasMore(boolean hasMore) {
        this.hasMore = hasMore;
    }

    /**
     * 点赞
     *
     * @param byEvaluatePersonId
     * @param customEvaluationId
     */
    private void supportEva(String byEvaluatePersonId, String customEvaluationId) {
        String url = Constant.URL_TEACHER + "EvaluateTeacher/likeNum";
        HashMap<String, String> map = new HashMap<>();
        map.put("operatorId", GetUserInfo.getStudentId(context));
        map.put("byEvaluatePersonId", byEvaluatePersonId);
        map.put("customEvaluationId", customEvaluationId);
        map.put("token", GetUserInfo.getToken(context));

        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

            }
        });
    }

    /**
     * 取消点赞
     *
     * @param customEvaluationId
     */
    private void unSupportEva(String customEvaluationId) {
        String url = Constant.URL_TEACHER + "EvaluateTeacher/delLikeNum";
        HashMap<String, String> map = new HashMap<>();
        map.put("operatorId", GetUserInfo.getStudentId(context));
        map.put("customEvaluationId", customEvaluationId);
        map.put("token", GetUserInfo.getToken(context));

        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

            }
        });
    }

    /**
     * 删除评论
     *
     * @param customEvaluationId
     */
    private void deleteEva(String customEvaluationId) {
        String url = Constant.URL_TEACHER + "EvaluateTeacher/delCustomEvaluation";
        HashMap<String, String> map = new HashMap<>();
        map.put("operatorId", GetUserInfo.getStudentId(context));
        map.put("customEvaluationId", customEvaluationId);
        map.put("token", GetUserInfo.getToken(context));

        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {

            }
        });
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.evaluate_custom_image)
        CircleImageView evaluateCustomImage;
        @Bind(R.id.evaluate_custom_name)
        TextView evaluateCustomName;
        @Bind(R.id.evaluate_custom_time)
        TextView evaluateCustomTime;
        @Bind(R.id.eva_support_iv)
        ImageView evaSupportIv;
        @Bind(R.id.eva_delete_iv)
        ImageView evaDeleteIv;
        @Bind(R.id.evaluate_custom_content)
        TextView evaluateCustomContent;
        @Bind(R.id.eva_support_count_tv)
        TextView evaSupportCountTv;

        public ItemViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    static class FooterViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.progressBar)
        ProgressBar progressBar;
        @Bind(R.id.load_text)
        TextView loadText;

        public FooterViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }
}
